<template>
  <div class="app-container">
    <!-- 条件查询   -->
    <el-form :inline="true" :model="query" size="mini" >
      <el-form-item label="用户名称:">
        <el-input v-model.trim="query.userName" placeholder="用户名称"></el-input>
      </el-form-item>
      <el-form-item label="状态:">
        <el-select v-model="query.status" clearable filterable style="width:120px;" placeholder="请选择">
          <el-option value="1" label="正常"></el-option>
          <el-option value="2" label="锁定"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" type="primary" @click="fetchUserList">查询</el-button>
        <el-button icon="el-icon-refresh" @click="reload">重置</el-button>
      </el-form-item>
    </el-form>

    <div>
      <el-button :disabled=" userRole !== 'SUPER_ADMIN' " size="small" type="primary" icon="el-icon-plus" @click="handleAdd()" style="margin-bottom: 20px;">添加</el-button>
      <el-button :disabled=" userRole !== 'SUPER_ADMIN' " size="small" type="danger" icon="el-icon-document-delete" @click="handleMultiDel()" style="margin-bottom: 20px;">删除</el-button>
      <el-button :disabled=" userRole !== 'SUPER_ADMIN' " size="small" plain type="primary" icon="el-icon-upload2" @click="importUser()" style="margin-bottom: 20px;">导入</el-button>
      <el-button :disabled=" userRole !== 'SUPER_ADMIN' " size="small" plain type="primary" icon="el-icon-download" @click="exportUser()" style="margin-bottom: 20px;">导出</el-button>
    </div>

    <!--  列表数据  -->
    <el-table :data="list" border style="width: 100%" ref="multipleTable" tooltip-effect="dark" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column align="center" label="序号" width="50" type="index"></el-table-column>
      <el-table-column align="center" prop="userName" label="用户名称" width="150"></el-table-column>
      <el-table-column align="center" prop="avatar" label="头像" width="120">
        <template slot-scope="scope">
          <el-image :src="scope.row.avatar" style="height: 40px;width: 40px;"></el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="roleName" label="角色名称" width="120"></el-table-column>
      <el-table-column align="center" prop="phone" label="手机号码" width="120"></el-table-column>
      <el-table-column align="center" prop="status" label="状态" width="90">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 2" type="danger">锁定</el-tag>
          <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="lastLoginTime" label="最近一次登录时间" width="160">
        <template slot-scope="scope">
          {{ getFormat(scope.row.lastLoginTime) }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="updateTime" label="更新时间" width="160">
        <template slot-scope="scope">
          {{ getFormat(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间" width="160">
        <template slot-scope="scope">
          {{ getFormat(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column  align="center" label="操作" >
        <template slot-scope="scope">
          <el-button icon="el-icon-search"
                     type="primary" size="mini"
                     @click="detail(scope.row.userId)">查看</el-button>
          <el-button icon="el-icon-edit"
                     type="success" size="mini"
                     @click="handleEdit(scope.row.userId)">编辑</el-button>
          <el-button icon="el-icon-document-delete"
                     type="danger" size="mini"
                     :disabled=" userRole !== 'SUPER_ADMIN' "
                     @click="handleDel(scope.row.userId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div style="margin-top: 10px;">
      <el-pagination background
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="query.pageNo"
                     :page-sizes="[10, 20, 50]"
                     :page-size="query.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="query.total">
      </el-pagination>
    </div>

    <el-drawer title="用户详情" :visible.sync="userDetailDrawer" direction="rtl" :before-close="handleCloseUserDetail" :wrapper-closable="false" size="40%">
      <el-form :model="userDetail" ref="formData" label-width="150px" label-position="right" style="margin-right: 20px;">
        <el-form-item label="用户名称：" prop="userName">
          <el-input  v-model="userDetail.userName" placeholder="用户名称" />
        </el-form-item>
        <el-form-item label="签名：" prop="userName" >
          <el-input  v-model="userDetail.sign" placeholder="签名" />
        </el-form-item>
        <el-form-item label="头像：" prop="avatar">
            <img :src="userDetail.avatar" class="avatar">
        </el-form-item>
        <el-form-item label="主页背景图：" prop="avatar">
          <img :src="userDetail.homepageCover" class="avatar">
        </el-form-item>
        <el-form-item label="角色：" prop="checkedRoleId">
          <el-select v-model="userDetail.roleId" clearable placeholder="请选择" >
            <el-option
              v-for="item in roleList"
              :key="item.roleId"
              :label="item.roleName"
              :disabled="item.roleCode === 'SUPER_ADMIN' "
              :value="item.roleId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组织：" prop="organization" v-if="userDetail.organizationList">
          <el-tag style="margin-right: 5px;" v-for="organizationItem in userDetail.organizationList">{{organizationItem.organizationName}}</el-tag>
        </el-form-item>
        <el-form-item label="性别：" prop="sex" >
          <el-radio-group v-model="userDetail.sex" >
            <el-radio :label = "1" border>男</el-radio>
            <el-radio :label = "2" border>女</el-radio>
            <el-radio :label = "3" border>保密</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号码：" prop="phone" >
          <el-input v-model="userDetail.phone" placeholder="手机号码" />
        </el-form-item>
        <el-form-item label="邮箱：" prop="email" >
          <el-input v-model="userDetail.email" placeholder="邮箱"  />
        </el-form-item>
        <el-form-item label="状态：" prop="status" >
          <el-radio-group v-model="userDetail.status" >
            <el-radio :label = "1" border>正常</el-radio>
            <el-radio :label = "2" border>锁定</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发言状态：" prop="speakStatus" >
          <el-radio-group v-model="userDetail.speakStatus" >
            <el-radio :label = "1" border>正常</el-radio>
            <el-radio :label = "2" border>锁定</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否展示粉丝列表：" prop="showFansList" >
          <el-radio-group v-model="userDetail.showFansList" >
            <el-radio :label = 1 border>展示</el-radio>
            <el-radio :label = 0 border>不展示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否展示分类列表：" prop="showCategoryList" >
          <el-radio-group v-model="userDetail.showCategoryList" >
            <el-radio :label = 1 border>展示</el-radio>
            <el-radio :label = 0 border>不展示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否展示收藏列表：" prop="showFavoriteList" >
          <el-radio-group v-model="userDetail.showFavoriteList" >
            <el-radio :label = 1 border>展示</el-radio>
            <el-radio :label = 0 border>不展示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="地址：" prop="address" >
          <el-input type="textarea" v-model="userDetail.address"  />
        </el-form-item>
      </el-form>
      <el-row style="margin-left: 40px">
        <el-button size="small" type="success" @click="handleCloseUserDetail">关闭</el-button>
      </el-row>
    </el-drawer>

    <el-drawer title="用户信息批量导入" :visible.sync="importUserDrawer" direction="rtl" :before-close="handleClose" :wrapper-closable="false" size="60%">

      <el-upload
          class="upload-demo"
          style="margin-left: 40px"
          drag
          action=""
          :http-request="batchImportUser"
          :show-file-list="false"
          >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">点击<el-link type="primary" @click="downloadUserTemplate">下载模板</el-link></div>
      </el-upload>

      <el-divider></el-divider>

      <el-table :data="importUserList" border style="width: 100%; margin-left: 40px;" ref="multipleTable" tooltip-effect="dark" >
        <el-table-column align="center" label="序号" width="50" type="index"></el-table-column>
        <el-table-column align="center" prop="userName" label="用户名称" width="120"></el-table-column>
        <el-table-column align="center" prop="sex" label="性别" width="70">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.sex === 1" type="danger">男</el-tag>
            <el-tag v-if="scope.row.sex === 2" type="success">女</el-tag>
            <el-tag v-if="scope.row.sex === 3" type="success">保密</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="phone" label="手机号码" width="120"></el-table-column>
        <el-table-column align="center" prop="email" label="邮箱地址" width="140"></el-table-column>
        <el-table-column align="center" prop="address" label="地址" width="200"></el-table-column>
        <el-table-column align="center" prop="errMsg" label="错误信息" ></el-table-column>
      </el-table>
      <div style="margin-left: 40px;margin-top: 20px;">
        <el-button type="primary" @click="batchSave()" :loading="loading">导入用户</el-button>
        <el-button type="danger"  @click="handleClose">取消</el-button>
      </div>

    </el-drawer>

    <el-drawer :title="title" :visible.sync="drawer" direction="rtl" :before-close="handleClose" :wrapper-closable="false">
      <el-form :model="user" ref="formData" label-width="150px" label-position="right" style="margin-right: 20px;">
        <el-form-item label="用户名称：" prop="userName">
          <el-input v-model="user.userName" placeholder="请输入用户名称" show-word-limit maxlength="32" clearable/>
        </el-form-item>
        <el-form-item label="签名：" prop="sign">
          <el-input v-model="user.sign" placeholder="请输入签名" show-word-limit maxlength="32" clearable/>
        </el-form-item>
        <el-form-item label="头像：" prop="avatar" >
          <el-upload class="avatar-uploader" action="" :show-file-list="false" :http-request="uploadAvatar">
            <img v-if="user.avatar" :src="user.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="主页背景图：" prop="homepageCover" >
          <el-upload class="avatar-uploader" action="" :show-file-list="false" :http-request="uploadHomepageCover">
            <img v-if="user.homepageCover" :src="user.homepageCover" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="角色：" prop="checkedRoleId">
          <el-select v-model="checkedRoleId" clearable placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.roleId"
              :label="item.roleName"
              :disabled="item.roleCode === 'SUPER_ADMIN' "
              :value="item.roleId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别：" prop="sex" >
          <el-radio-group v-model="user.sex" >
            <el-radio :label = "1" border>男</el-radio>
            <el-radio :label = "2" border>女</el-radio>
            <el-radio :label = "3" border>保密</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号码：" prop="phone" >
          <el-input v-model="user.phone" placeholder="手机号码" />
        </el-form-item>
        <el-form-item label="邮箱：" prop="email" >
          <el-input v-model="user.email" placeholder="邮箱"  />
        </el-form-item>
        <el-form-item label="状态：" prop="status" >
          <el-radio-group v-model="user.status" >
            <el-radio :label = "1" border>正常</el-radio>
            <el-radio :label = "2" border>锁定</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发言状态：" prop="speakStatus" >
          <el-radio-group v-model="user.speakStatus" >
            <el-radio :label = "1" border>正常</el-radio>
            <el-radio :label = "2" border>锁定</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否展示粉丝列表：" prop="showFansList" >
          <el-radio-group v-model="user.showFansList" >
            <el-radio :label = "1" border>展示</el-radio>
            <el-radio :label = "0" border>不展示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否展示分类列表：" prop="showCategoryList" >
          <el-radio-group v-model="user.showCategoryList" >
            <el-radio :label = "1" border>展示</el-radio>
            <el-radio :label = "0" border>不展示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否展示收藏列表：" prop="showFavoriteList" >
          <el-radio-group v-model="user.showFavoriteList" >
            <el-radio :label = "1" border>展示</el-radio>
            <el-radio :label = "0" border>不展示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="地址：" prop="address" >
          <el-input type="textarea" v-model="user.address"  />
        </el-form-item>
      </el-form>
      <el-row style="margin-left: 40px">
        <el-button size="small" type="danger" plain @click="handleClose">取消</el-button>
        <el-button v-permission=" ['USER:EDIT'] " size="small" type="success" @click="submit()" :loading="loading">提交</el-button>
      </el-row>
    </el-drawer>

  </div>
</template>
<script>
import { dateFormat } from '@/utils/date';
import { userList, createUser, editUser, getUserInfo, deleteUser, batchImportUser, batchCreate, exportUser, userDetail } from "@/api/user";
import { uploadFile } from "@/api/file";
import { getRoles } from "@/api/auth";
import { downloadUserImportTemplate } from "@/api/file";
import { USER_AVATAR, USER_HOMEPAGE } from "@/utils/fileType";
import { getUserRole } from "@/utils/userToken";

export default {
  data() {
    return {
      query: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      },
      list: [],
      roleList: [],
      checkedCategoryIds: [],
      drawer: false,
      title: "添加用户",
      category: {},
      loading: false,
      valid: true,
      roleCode: '',
      user: {},
      checkedRoleId: '',
      checkedUserIds: [],
      checkedUsers: [],
      importUserDrawer: false,
      importUserList: [],
      userDetailDrawer: false,
      userDetail: {},
      userRole: ''
    }
  },

  created() {
    this.fetchUserList();
    this.getAllRoles();

    this.userRole = getUserRole();
  },

  methods: {
    // 查询用户列表
    fetchUserList() {
      userList(this.query).then(res => {
        if (res.code === 200) {
          this.list = res.data.list;
          this.query.total = res.data.total;
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    // 导出用户
    exportUser() {
      console.log("选择导出的用户：", this.checkedUserIds)
      if (this.checkedUserIds.length === 0) {
        this.$notify.error({
          title: '错误',
          message: '请至少选择一个用户',
          duration: 1500
        });
        return;
      }

      const data = {
        userIds: this.checkedUserIds
      }
      exportUser(data).then(res => {
        const blob = new Blob([res.data]);
        const a = document.createElement("a");
        const href = window.URL.createObjectURL(blob);
        a.href = href;
        a.download = '用户信息.xlsx';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(href);
      })
    },

    // 查看详情
    detail(id) {
      userDetail(id).then(res => {
        if (res.code === 200) {
          this.userDetailDrawer = true;
          this.userDetail = res.data;
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    // 关闭用户详情弹框
    handleCloseUserDetail() {
      this.userDetailDrawer = false;
      this.userDetail = {};
    },

    importUser() {
      this.importUserDrawer = true;
    },

    // 批量保存
    batchSave() {
      this.loading = true;
      const data = {
        list: this.importUserList
      }
      batchCreate(data).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '保存成功',
            type: 'success',
            duration: 1500
          });
          this.handleClose();
          this.loading = false;
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
          this.loading = false;
        }
      })
    },

    // 批量导入用户信息
    batchImportUser(file) {
      const data = new FormData();
      data.append('file', file.file);
      batchImportUser(data).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '上传成功',
            type: 'success',
            duration: 1500
          });
          this.importUserList = res.data;
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    // val 是切换之后的每页显示多少条
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.fetchUserList();
    },

    // 当页码改变后触发此方法 val是当前点击（或输入）的页码
    handleCurrentChange(val) {
      this.query.pageNo = val;
      this.fetchUserList();
    },

    // 获取所有的角色信息
    getAllRoles() {
      getRoles().then(res => {
        if (res.code === 200) {
          this.roleList = res.data;
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    // 删除
    handleDel(id) {
      this.$confirm('确认删除这条记录吗?删除后，该分类下的标签均被删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        const data = {
          userIds: []
        }
        data.userIds.push(id)
        deleteUser(data).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: response.message,
              duration: 1500
            });
          }
          // 刷新列表
          this.fetchUserList();
        })
      }).catch(() => {
        // 取消删除
      });
    },

    // 批量删除
    handleMultiDel() {
      if (this.checkedUserIds.length === 0) {
        this.$notify.error({
          title: '错误',
          message: '请至少选择一个用户',
          duration: 1500
        });
        return;
      }

      this.$confirm('确认删除这条记录吗?删除后，该用户发表的文章也将被删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        const data = {
          userIds: []
        }
        data.userIds = this.checkedUserIds;
        deleteUser(data).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: response.message,
              duration: 1500
            });
          }
          // 刷新列表
          this.fetchUserList();
          this.checkedUserIds = [];
        })
      }).catch(() => {
        // 取消删除
        console.log("取消")
        this.checkedUserIds = []
      });
    },

    // 编辑
    handleEdit(id) {
      this.title = "编辑用户"
      this.drawer = true;

      getUserInfo(id).then(res => {
        if (res.code === 200) {
          this.user = res.data
          this.checkedRoleId = res.data.roleId
        }
      })
    },

    // 新增用户
    handleAdd() {
      this.drawer = true;
    },

    // 重置
    reload() {
      this.query.userName = '';
      this.query.status = '';
      this.fetchUserList();
    },

    // 格式化日期
    getFormat(date){
      if (date) {
        return dateFormat(date);
      }
      return ""
    },

    downloadUserTemplate() {
      downloadUserImportTemplate().then(res => {
        if (res.code === 200) {
          window.location.href = res.data;
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    // 关闭弹框
    handleClose(done) {
      this.drawer = false;
      this.title = "添加用户"
      this.loading = false;
      this.user = {}
      this.fetchUserList();
      this.checkedRoleId = '';
      this.importUserDrawer = false;
      this.importUserList = []
    },

    handleSelectionChange(val) {
      this.checkedUserIds = [];
      let len = JSON.parse(JSON.stringify(val))
      if (len.length !== 0) {
        for (let i = 0; i < len.length; i++) {
          this.checkedUserIds.push(len[i].userId)
        }
      } else {
        this.checkedUserIds = len
      }
    },

    // 上传个人主页背景图
    uploadHomepageCover(file) {
      const data = new FormData();
      data.append('file', file.file);
      data.append('type', USER_HOMEPAGE);
      uploadFile(data).then(response => {
        // 将之前的图片删除
        if(response.code === 200) {
          this.user.homepageCover = response.data;
          this.getAllRoles();
        } else {
          this.$notify.error({
            title: '错误',
            message: response.message,
            duration: 1500
          });
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '上传失败'
        })
      })
    },

    // 上传个人头像
    uploadAvatar(file){
      const data = new FormData();
      data.append('file', file.file);
      data.append('type', USER_AVATAR);
      uploadFile(data).then(response => {
        // 将之前的图片删除
        // this.deleteImage();
        if(response.code === 200) {
          this.user.avatar = response.data;
          this.getAllRoles();
        } else {
          this.$notify.error({
            title: '错误',
            message: response.message,
            duration: 1500
          });
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '上传失败'
        })
      })
    },


    // 提交
    submit() {
      this.loading = true;
      this.beforeSubAndEdit();
      if (!this.valid) {
        this.valid = true;
        this.loading = false;
        return;
      }

      this.user.roleId = this.checkedRoleId;
      if (this.title === '添加用户') {
        // 添加
        createUser(this.user).then(res => {
          if (res.code === 200) {
            this.$notify({
              title: '成功',
              message: '用户添加成功',
              type: 'success',
              duration: 1500
            });
            this.handleClose();
          } else {
            this.$notify.error({
              title: '错误',
              message: res.message,
              duration: 1500
            });
          }
        })
        this.valid = true;
        this.loading = false;
      } else {
        // 编辑
        this.valid = true;
        this.loading = false;

        editUser(this.user).then(res => {
          if (res.code === 200) {
            this.$notify({
              title: '成功',
              message: '用户编辑成功',
              type: 'success',
              duration: 1500
            });
            this.handleClose();
          } else {
            this.$notify.error({
              title: '错误',
              message: res.message,
              duration: 1500
            });
            this.valid = true;
            this.loading = false;
          }
        })
      }
    },

    beforeSubAndEdit() {
      if (!this.user.userName) {
        this.$notify.error({
          title: '错误',
          message: '请输入用户名称',
          duration: 1500
        });
        this.valid = false
        return
      }

      if (!this.user.avatar) {
        this.$notify.error({
          title: '错误',
          message: '请上传头像',
          duration: 1500
        });
        this.valid = false
        return
      }

      if (this.title !== '添加用户' && !this.checkedRoleId) {
        this.$notify.error({
          title: '错误',
          message: '请选择角色',
          duration: 1500
        });
        this.valid = false
        return
      }

      if (this.user.phone) {
        if (this.user.phone.length !== 11) {
          this.$notify.error({
            title: '错误',
            message: '手机号码不合法！',
            duration: 1500
          });
          this.valid = false;
        }
      }

    },


  }
}
</script>



<style>
.el-drawer.rtl{
  overflow: scroll;
}
</style>
